﻿#region Copyright
//       Copyright (c) 2009 - Antoine Jaussoin - http://www.jaussoin.com/blog/
// 
//        This program is free software: you can redistribute it and/or modify
//        it under the terms of the GNU General Public License as published by
//        the Free Software Foundation, either version 3 of the License, or
//        (at your option) any later version.
// 
//        This program is distributed in the hope that it will be useful,
//        but WITHOUT ANY WARRANTY; without even the implied warranty of
//        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//        GNU General Public License for more details.
// 
//        You should have received a copy of the GNU General Public License
//        along with this program.  If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace FT.Architecture.Utils.ExtensionMethods
{
    /// <summary>
    /// Extension methods for Decimals
    /// </summary>
    public static class DecimalExtensions
    {
        /// <summary>
        /// Remove trailing zeros off a decimal, but always maintaining a minimum
        /// number of decimal Places.  For example 10.234000 with minDP as 4 would
        /// give 10.2340, whereas with minDP as 3 would give 10.234 and with 2 would
        /// also give 1.234 as this is the *min* dp
        /// </summary>
        /// <param name="value"></param>
        /// <param name="minDp"></param>
        /// <returns></returns>
        public static string RemoveTrailingZeros(this decimal value, int minDp)
        {
            if (minDp < 0)
                minDp = 0;

            // get rid of the zeros and . if necessary first
            string result = value.ToString().TrimEnd(new[] {'.', '0'});

            // now ensure it's at least midDp decimal places
            string roundedResult = string.Format("{0:N" + minDp + "}", value);

            // return the longer one
            return result.Length < roundedResult.Length ? roundedResult : result;
        }
    }
}